#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <cassert>

using namespace std;

int main(int argc, char* argv[])
{
    assert(argc == 2);

    // 获取目标主机信息
    char* host = argv[1];
    struct hostent* hostinfo = gethostbyname(host);
    assert(hostinfo);

    // 获取daytime服务信息
    struct servent* servinfo = getservbyname("daytime", "tcp");
    assert(servinfo);
    cout << "daytime port is " << ntohs(servinfo->s_port) << endl;

    struct sockaddr_in address;
    address.sin_family = AF_INET;
    address.sin_port = servinfo->s_port;
    address.sin_addr = *((struct in_addr*)hostinfo->h_addr_list[0]);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);

    int ret = connect(sockfd, (struct sockaddr*)&address, sizeof(address));
    assert(ret != -1);

    char buffer[128];
    ret = read(sockfd, buffer, sizeof(buffer));
    assert(ret > 0);
    buffer[ret] = '\0'; // 确保字符串以null结尾
    cout << "the day time is: " << buffer << endl;

    close(sockfd);

    return 0;
}